﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web.Http;
using Weather.Models;
using Weather.Services;
using static Weather.Models.WeatherModel;
using Dapper;
using System.Text.RegularExpressions;
using System.Diagnostics;

namespace Weather.Controllers
{
    public class WeatherController : ApiController
    {
        public static string HttpGet(string Url)
        {
            System.Net.HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            request.Proxy = null;
            request.KeepAlive = false;
            request.Method = "GET";
            request.ContentType = "application/json; charset=UTF-8";
            request.AutomaticDecompression = DecompressionMethods.GZip;

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();
            if (response != null)
            {
                response.Close();
            }
            if (request != null)
            {
                request.Abort();
            }

            return retString;
        }

        [HttpGet]
        [ActionName("WeatherInterface")]
        public bool WeatherInterface(string city_id)
        {
            bool boole = false;
            //获取Json串
            string url = string.Format("http://www.weather.com.cn/data/sk/{0}.html", city_id);
            string result = HttpGet(url);
            try
            {
                WeatherModel weathermodel = JsonConvert.DeserializeObject<WeatherModel>(result);
            }
            catch (Exception e)
            {
                int i = 1;
                Trace.WriteLine(e.Message+result);
                FileStream fs = new FileStream(@"C:\MySoftware\文档\Weather\Weather\ErrorLogs\JsonConvertLog.txt", FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
                StreamWriter sw = new StreamWriter(fs);
                sw.WriteLine("———#———第" + i + "条数据———#———"+"时间:"+DateTime.Now.ToString()+"地区号:"+city_id+"#异常记录:" +e.Message + "从网络接到的数据" + result );
                return false;
            }
           
            dbdao dd = new dbdao();
            IDbConnection nconnection = dd.LoadFromFile();
            //先根据传进来的参数进行查询
            string queryNum = string.Format("select count(*) from weather_info where city_no = {0}",city_id);
            string queryTime = string.Format("select time from weather_info where city_no = {0}",city_id);
            int QueryResult = nconnection.Query<int>(queryNum).SingleOrDefault();
            if (QueryResult == 0)
            {
                //SQL语句插入
                string insert = string.Format("insert into weather_info values('{0}','{1}','{2}')", city_id, result, DateTime.Now.ToString());
                try
                {

                    int i = nconnection.Execute(insert);
                    if (i != 1)
                    {
                        Trace.WriteLine("############$$$$$$$$$$$$$$$###########$$$$$$$$$$\n");
                    }
                    boole = true;
                }
                catch (Exception e)
                {
                    boole = false;
                    Trace.WriteLine(e.Message);
                }
            }

            if(QueryResult == 1)
            {
                DateTime timeTrial = nconnection.Query< DateTime>(queryTime).SingleOrDefault();
                DateTime timeNow = DateTime.Now;
                TimeSpan tspan = timeNow.Subtract(timeTrial);
                int hourSpan = tspan.Hours;
                if(hourSpan <= 6)
                {
                    Trace.WriteLine("#################未满6小时，刚刚过了"+hourSpan+"小时，不需要更新数据################");
                    return false;
                }
                if(hourSpan > 6)
                {
                    
                    string update = string.Format("update weather_info set weather_data = '{0}',time = '{1}'",result,DateTime.Now.ToString());
                    nconnection.Execute(update);
                    Trace.WriteLine("################成功更新数据！########################");
                    boole = true;
                }
            }
            nconnection.Close();
            Trace.WriteLine(boole);
            return boole;
        }

        /*
        /// <summary>
        /// 批量提取 城市代码.txt 当中的数字代码，并写入aaa文件
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ActionName("WeatherAuto")]
        public bool WeatherAuto()
        {
            bool bools = false;
            //string messages="";
            Regex reg = new Regex(@"[\d]+");
            
            string str = System.IO.File.ReadAllText(@"C: \Users\Whale_Sun\Desktop\城市代码.txt");
            //FileStream fs = new FileStream(@"C: \Users\Whale_Sun\Desktop\城市代码.txt",FileMode.Open);

            MatchCollection mcs = reg.Matches(str);
            foreach (Match mc in mcs)
            {
                FileStream fs = new FileStream(@"C:\Users\Whale_Sun\Desktop\aaa.txt",FileMode.Append,FileAccess.Write,FileShare.ReadWrite);
                StreamWriter sw = new StreamWriter(fs); 
                sw.WriteLine(mc);
                sw.Flush();
                sw.Close();  
                fs.Close();
                bools = true;
            }

            return bools; 
            //return messages;
        }*/

       /// <summary>
        /// 用于测试中国气象局api的最大请求次数，没有限制
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ActionName("WeatherReadLine")]
        public bool WeatherReadLine()
        {
            
            string line = "";
            StreamReader sr = new StreamReader(@"C:\MySoftware\文档\Weather\Weather\config\aaa.txt");
            while(true)
            {
                line = sr.ReadLine();
                if (!String.IsNullOrEmpty(line))
                {
                     WeatherInterface(line);
                }
                else
                {
                    break;
                }
            }
            return true;

        }


    } 
}

